package com.umeox.auto_update

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.umeox.base.BaseRecyclerViewAdapter
import com.umeox.sdk_ring.RingScanCallback
import com.umeox.sdk_ring.UMScanResult
import com.umeox.sdk_ring.scan.RingDirectScanner

class DeviceTypeSelectBottomSheetDialog : BaseRecyclerViewAdapter.OnItemClickListener<String> {

    private lateinit var dialog: BottomSheetDialog
    private lateinit var rv: RecyclerView
    private lateinit var adapter: DeviceTypeListAdapter

    private var callback: DeviceTypeSelectCallback? = null

    private val deviceNameList = arrayListOf<String>()

    @SuppressLint("MissingPermission")
    private val call: RingScanCallback = object : RingScanCallback {
        override fun onScanResult(result: UMScanResult) {
            var deviceName = result.device.name
            if (!TextUtils.isEmpty(deviceName) && deviceName.contains("-")) {
                deviceName = deviceName.split("-")[0] + "-.*"
            }
            if (TextUtils.isEmpty(deviceName) || deviceNameList.contains(deviceName)) {
                return
            }
            deviceNameList.add(deviceName)
            Handler(Looper.getMainLooper()).post {
                adapter.refreshData(deviceNameList)
            }
        }
    }

    private val scannerManager = RingDirectScanner(this, call, arrayListOf())

    fun init(context: Context) {
        dialog = BottomSheetDialog(context)
        val view = LayoutInflater.from(context).inflate(R.layout.dialog_device_type_select, null)
        rv = view.findViewById(R.id.rvDevice)
        adapter = DeviceTypeListAdapter()
        rv.adapter = adapter
        adapter.setOnItemClickListener(this)
        dialog.setContentView(view)

    }

    fun setDeviceTypeSelectCallback(deviceTypeSelectCallback: DeviceTypeSelectCallback) {
        callback = deviceTypeSelectCallback
    }

    fun show() {
        scannerManager.startScan()
        Handler(Looper.getMainLooper()).postDelayed({
            scannerManager.stopScan()
        },15*1000)
        if (!dialog.isShowing) {
            dialog.show()
        }
    }

    fun dismiss() {
        scannerManager.stopScan()
        if (dialog.isShowing) {
            dialog.dismiss()
        }
    }


    interface DeviceTypeSelectCallback {
        fun onDeviceTypeSelect(deviceName: String)
    }

    override fun onItemClick(view: View?, position: Int, t: String) {
        callback?.onDeviceTypeSelect(t)
        dismiss()
    }

}